package com.notification;

import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Vibrator;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

import com.alarm.Alarm;
import com.alarm.DateTime;
import com.alarm.R;
import com.alarm.WakeMeUp;
import com.gesture.GestureControlActivity;
import com.voice.VoiceControlActivity;

public class AlarmNotification extends Activity {
	private static final int GESTURE_CONTROL_ACTIVITY = 10;

	private static final int VOICE_CONTROL_ACTIVITY = 0;

	private final String TAG = "AlarmNotification";

	private Ringtone mRingtone;
	private Vibrator mVibrator;
	private final long[] mVibratePattern = { 0, 500, 500 };
	private boolean mVibrate;
	private Uri mAlarmSound;
	private long mPlayTime;
	private Timer mTimer = null;
	private Alarm mAlarm;
	private DateTime mDateTime;
	private TextView mTextView;
	private PlayTimerTask mTimerTask;
	private NotificationSetting setting = new NotificationSetting();

	@Override 
	protected void onCreate(Bundle bundle) {
		super.onCreate(bundle);

		getWindow().addFlags(
				WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
						| WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
						| WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);

		setContentView(R.layout.notification);

		mDateTime = new DateTime(this);
		mTextView = (TextView) findViewById(R.id.alarm_title_text);

		readPreferences();

		mRingtone = RingtoneManager.getRingtone(getApplicationContext(),
				mAlarmSound);
		if (mVibrate)
			mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

		start(getIntent());
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		Log.i(TAG, "AlarmNotification.onDestroy()");

		stop();
		finish();
	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		Log.i(TAG, "AlarmNotification.onNewIntent()");

		addNotification(mAlarm);

		stop();
		start(intent);
	}

	private void start(Intent intent) {
		mAlarm = new Alarm(this);
		mAlarm.fromIntent(intent); 
		Log.i(TAG, "AlarmNotification.start('" + mAlarm.getTitle() + "')");
		mTextView.setText(mAlarm.getTitle());
		if (mVibrate)
			mVibrator.vibrate(mVibratePattern, 0);
		mTimerTask = new PlayTimerTask();
		mTimer = new Timer(); 
		mTimer.schedule(mTimerTask, mPlayTime);
		mRingtone.play();
		if (mVibrate)
			mVibrator.vibrate(mVibratePattern, 0);
	}

	private void stop() {
		Log.i(TAG, "AlarmNotification.stop()");
		mRingtone.stop();
		if (mVibrate)
			mVibrator.cancel();
		mTimer.cancel();
		mRingtone.stop();
		if (mVibrate)
			mVibrator.cancel();
	}
	public void onDismissClick(View view) {
		stop();
		if (setting.isGesture())
			gestureDetect();
		else if (setting.isVoice())
				voiceDetect();
		else finish();
	}
	
	
	private boolean voiceDetect() {
		Log.d(TAG, "AlarmNotification.VoiceDetect");
		Intent intent = new Intent(getBaseContext(), VoiceControlActivity.class);
		intent.putExtra("voice", setting.getVoice());
		startActivityForResult(intent, VOICE_CONTROL_ACTIVITY);
		return true;
	}

	private boolean gestureDetect() {
		Log.d(TAG, "AlarmNotification.gestureDetect");
		Intent intent = new Intent(getBaseContext(), GestureControlActivity.class);
		intent.putExtra("gesture", setting.getGesture());
		startActivityForResult(intent, GESTURE_CONTROL_ACTIVITY);
		return true;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		
		mTimer.cancel();
		switch (requestCode) {
		case GESTURE_CONTROL_ACTIVITY:
			if (resultCode == RESULT_OK)
				if(data.getIntExtra("status", -1)==1){
					onDestroy();
				} else{
					start(this.getIntent());
				}
				break;
		case VOICE_CONTROL_ACTIVITY:
		if (resultCode == RESULT_OK)
			if(data.getIntExtra("status", -1)==1){
				onDestroy();
			} else{
				start(this.getIntent());
			}
			break;
		default:;			
		}
	}
	
	private void readPreferences() {
		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(this);

		mAlarmSound = Uri.parse(prefs.getString("alarm_sound_pref",
				"DEFAULT_RINGTONE_URI"));
		mVibrate = prefs.getBoolean("vibrate_pref", true);
		mPlayTime = (long) Integer.parseInt(prefs.getString(
				"alarm_play_time_pref", "30")) * 1000;
		setting.load();
	}

	private void addNotification(Alarm alarm) {
		NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
		Notification notification;
		PendingIntent activity;
		Intent intent;

		Log.i(TAG, "AlarmNotification.addNotification(" + alarm.getId() + ", '"
				+ alarm.getTitle() + "', '" + mDateTime.formatDetails(alarm)
				+ "')");

		notification = new Notification(R.drawable.ic_notification,
				"Missed com.alarm", System.currentTimeMillis());
		notification.flags |= Notification.FLAG_AUTO_CANCEL;

		intent = new Intent(this.getApplicationContext(), WakeMeUp.class);
		intent.setAction(Intent.ACTION_MAIN);
		intent.addCategory(Intent.CATEGORY_LAUNCHER);

		activity = PendingIntent.getActivity(this, (int) alarm.getId(), intent,
				PendingIntent.FLAG_UPDATE_CURRENT);
		notification.setLatestEventInfo(this,
				"Missed com.alarm: " + alarm.getTitle(),
				mDateTime.formatDetails(alarm), activity);

		notificationManager.notify((int) alarm.getId(), notification);
	}

	@Override
	public void onBackPressed() {
		finish();
	}

	private class PlayTimerTask extends TimerTask {
		@Override
		public void run() {
			Log.i(TAG, "AlarmNotification.PlayTimerTask.run()");
			addNotification(mAlarm);
			finish();
		}
	}
}

